<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/6/6
 * Time: 上午10:21
 */

namespace backend\controllers;

use common\controllers\BaseControllers;
use common\models\ar\PermissionMenus;

class BackendController extends BaseControllers
{
    public $layout = "backend";

    /**
     * 根据代理级别、是否是管理账户获取菜单
     * 默认只有两级
     *
     * @param int $level 代理级别
     *
     * @return array
     */
    protected function getMenus($level)
    {
        if ($level>=4){
            $level=4;
        }
        $tmp = PermissionMenus::find()->select('level')->distinct()->orderBy('level asc')->all();
        $menus = [];
        foreach ($tmp as $t) {
            $tmpMenus = PermissionMenus::find()->where([
                'level' => $t->level,
                'show_flag' => 1
            ])->orderBy('sort asc,id asc')->all();

            foreach ($tmpMenus as $r) {
//                var_dump($r['condition']);
//                exit();
                if (!in_array($level, explode(',', $r['condition']))) {
                    //当前级别无权限
                    continue;
                }
                if ($r['level'] == 1) {
                    $menus['menu_' . $r['id']] = [
                        'id' => $r['id'],
                        'level' => $r['level'],
                        'sort' => $r['sort'],
                        'show_flag' => $r['show_flag'],
                        'name' => $r['name'],
                        'selected' => $r['selected'],
                        'type' => $r['type'],
                        'route' => $r['route'],
                        'params' => $r['params'],
                        'onclick' => $r['onclick'],
                        'icon' => $r['icon'],
                        'childNum' => 0,
                        'child' => [],
                    ];
                } else {
                    if (!isset($menus['menu_' . $r['pid']]['show_flag'])) {
                        //父级不显示，子级也不显示
                        continue;
                    }

                    $menus['menu_' . $r['pid']]['childNum']++;
                    $menus['menu_' . $r['pid']]['child']['menu_' . $r['id']] = [
                        'id' => $r['id'],
                        'pid' => $r['pid'],
                        'level' => $r['level'],
                        'sort' => $r['sort'],
                        'name' => $r['name'],
                        'selected' => $r['selected'],
                        'type' => $r['type'],
                        'route' => $r['route'],
                        'params' => $r['params'],
                        'onclick' => $r['onclick'],
                    ];
                }
            }
        }

        return $menus;
    }
}
